<template>
  <div class="createPolicy">
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <!-- <el-breadcrumb-item>
                    <i class="el-icon-s-promotion"></i> 车辆配置
                </el-breadcrumb-item> -->
        <el-breadcrumb-item> 采集策略配置</el-breadcrumb-item>
        <el-breadcrumb-item> 创建新策略</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="content">
      <div class="main">
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          class="demo-ruleForm"
          label-width="120px"
          status-icon
          style="width: 50%"
        >
          <el-form-item label="提出部门" prop="demandDepartment">
            <el-input v-model="ruleForm.demandDepartment" />
          </el-form-item>
          <el-form-item label="开发部门" prop="developDepartment">
            <el-input v-model="ruleForm.developDepartment" />
          </el-form-item>
          <el-form-item label="策略类型" prop="scFlag">
            <!-- false 表示 trigger，  true 表示sc -->
            <el-select
              v-model="ruleForm.scFlag"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option label="trigger" :value="false"> </el-option>
              <el-option label="SC" :value="true"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="ID" prop="id">
            <el-input
              v-model="ruleForm.id"
              min="0"
              oninput="value=value.replace(/[^\d]/g,'')"
            />
          </el-form-item>
          <el-form-item label="场景" prop="sceneId">
            <el-select
              v-model="ruleForm.sceneId"
              placeholder=""
              style="width: 85%"
            >
              <el-option
                v-for="item in sceneOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>

            <el-button
              style="width: 10%; margin-left: 10px"
              type="text"
              @click="createScene"
              >新建场景
            </el-button>
          </el-form-item>
          <el-form-item label="策略名称" prop="strategyName">
            <el-input v-model="ruleForm.strategyName" />
          </el-form-item>
          <el-form-item label="策略描述" prop="strategyDesc">
            <el-input v-model="ruleForm.strategyDesc" />
          </el-form-item>

          <el-form-item label="数据包内容" prop="content">
            <el-input v-model="ruleForm.content" />
          </el-form-item>

          <el-form-item label="优先级" prop="priority" style="width: 100%">
            <template #label>
              优先级
              <el-tooltip class="box-item" effect="light" placement="top-start">
                <template #content>
                  <div v-if="projectNameIsJ3">
                    优先级：1【紧急】<br />
                    优先级：2【高优】<br />
                    优先级：3【普通】
                  </div>
                  <div v-else>
                    优先级：1-3 【普通】<br />
                    优先级：4-7 【车端 - 高优先(算法) 云端 - 高优】<br />
                    优先级：8-10【车端/云端 - 紧急】
                  </div>
                </template>
                <i
                  class="el-icon-warning-outline"
                  style="
                    width: 2%;
                    font-weight: bold;
                    cursor: pointer;
                    margin-right: 1%;
                  "
                ></i>
              </el-tooltip>
            </template>
            <el-select
              v-model="ruleForm.priority"
              placeholder=""
              style="width: 100%"
            >
              <el-option
                v-for="item in 10"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-row style="height: 40px; padding-left: 15px" class="no-margin-left">
            <el-form-item
              label="采集时长"
              style="padding-left: 5px; padding-right: 10px"
            >
              <el-col style="font-weight: lighter; width: 50px"> 触发前</el-col>
            </el-form-item>
            <el-form-item>
              <el-input-number
                v-model="collectTimeBefore"
                controls-position="right"
                @change="beforeTriggering"
                :min="0"
                :max="15"
                label="描述文字"
                style="width: 135px"
              ></el-input-number>
            </el-form-item>
            <el-form-item style="width: 10px" />
            <el-form-item>
              <el-col style="font-weight: lighter"> ~</el-col>
            </el-form-item>
            <el-form-item style="width: 10px" />
            <el-form-item
              style="color: black; padding-left: 5px; padding-right: 10px"
            >
              <el-col style="font-weight: lighter; width: 50px"> 触发后</el-col>
            </el-form-item>
            <el-form-item>
              <el-input-number
                v-model="collectTimeAfter"
                controls-position="right"
                @change="afterTriggering"
                :min="0"
                :max="14"
                label="描述文字"
                style="width: 130px"
              />
            </el-form-item>
          </el-row>

          <!--                    <el-form-item label="状态" prop="status">-->
          <!--                        <el-select v-model="ruleForm.status" placeholder="" style="width: 100%">-->
          <!--                            <el-option-->
          <!--                                v-for="item in statusOptions"-->
          <!--                                :key="item.value"-->
          <!--                                :label="item.label"-->
          <!--                                :value="item.value"-->
          <!--                            />-->
          <!--                        </el-select>-->
          <!--                    </el-form-item>-->

          <el-form-item label="单日采集次数" prop="count">
            <el-input-number v-model="count" @change="countChange"/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)"
              >提交</el-button
            >
            <el-button type="primary" @click="returnBack">返回</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <NewScene ref="newScene" @feedback="feedback" />
  </div>
</template>

<script>
import { onMounted, reactive, ref, toRaw, watch, computed } from "vue";
import NewScene from "./components/NewScene.vue";
import {
  getSceneListApi,
  strategyCreatApi,
} from "@/api/carManage/policyManage.js";
import { ElMessage } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
export default {
  components: {
    NewScene,
  },
  setup() {
    // J3的故障等级是1（紧急）2（高优）3（普通）,暂不修改逻辑，只更新文本描述，20240103
    // const priorityOptions = ref([
    //     {
    //         value: 2,
    //         label: '普通',
    //     }, {
    //         value: 4,
    //         label: '高优',
    //     }, {
    //         value: 10,
    //         label: '紧急',
    //     },
    // ]);
    const statusOptions = ref([
      {
        value: 0,
        label: "暂停",
      },
      {
        value: 1,
        label: "启用",
      },
    ]);

    const ruleFormRef = ref();
    const ruleForm = reactive({
      demandDepartment: "",
      developDepartment: "",
      scFlag: null,
      id: "",
      sceneId: "",
      strategyName: "",
      strategyDesc: "",
      content: "",
      priority: "",
      status: 0,
      createBy: "",
      collectTimeBefore: 8,
      collectTimeAfter: 6,
      count: 100
    });


    const collectTimeBefore = ref(8);
    const collectTimeAfter = ref(6);
    const count = ref(100);
    const creator = ref("");

    const rules = reactive({
      demandDepartment: [
        { required: true, message: "请输入需求部门", trigger: "blur" },
      ],
      developDepartment: [
        { required: true, message: "请输入开发部门", trigger: "blur" },
      ],
      scFlag: [{ required: true, message: "请选择策略类型", trigger: "blur" }],
      id: [{ required: true, message: "请输入ID", trigger: "blur" }],
      sceneId: [{ required: true, message: "请选择场景", trigger: "blur" }],
      strategyName: [
        { required: true, message: "请输入策略名称", trigger: "blur" },
      ],
      strategyDesc: [
        { required: true, message: "请输入策略描述", trigger: "blur" },
      ],
      content: [
        { required: true, message: "请输入数据包内容", trigger: "blur" },
      ],
      priority: [{ required: true, message: "请选择优先级", trigger: "blur" }],
      count: [
        { required: true, message: "请输入单日采集次数", trigger: "blur" },
      ],
    //   status: [{ required: true, message: "请选择状态", trigger: "blur" }],
    });
    const store = useStore();
    const projectObj = computed(() => store.state.projectObj);
    // 判断项目名称是否包含J3,若包含则更新优先级的文案描述
    const projectNameIsJ3 = computed(() => {
      if (projectObj && projectObj.value.name) {
        let projectName = projectObj.value.name;
        return projectName.indexOf("J3") > -1;
      } else {
        return false;
      }
    });
    const route = useRoute();
    watch(
      () => route.query.key,
      () => {
        for (let k in ruleForm) {
          ruleForm[k] = "";
        }
        ruleForm.status = 0;
        try {
          creator.value = JSON.parse(
            localStorage.getItem("userInfo")
          ).employeeId;
          ruleForm.createBy = creator.value;
        } catch (e) {}
      },
      {
        immediate: true,
      }
    );
    const router = useRouter();
    const submitForm = async (formEl) => {
      let req = toRaw(ruleForm);
      if (!formEl) return;
      await formEl.validate((valid, fields) => {
        if (valid) {
          strategyCreatApi(req).then((res) => {
            if (res.data.data == 1) {
              ElMessage({
                message: "创建成功",
                type: "success",
              });
              router.replace({
                path: "/triggerConfiguration/PolicyManage",
                query: {
                  key: +new Date(),
                },
              });
            } else {
              ElMessage({
                message: "创建失败",
                type: "error",
              });
            }
          });
        }
      });
    };
    const returnBack = () => {
      router.push({
        path: "/triggerConfiguration/PolicyManage",
      });
    };
    const newScene = ref(null);
    const createScene = () => {
      newScene.value.switchVisible();
    };
    const sceneOptions = ref([]);
    const getSceneListFn = () => {
      getSceneListApi({}).then((res) => {
        if (res.data.code == 200) {
          sceneOptions.value = res.data.data;
        }
      });
    };
    const feedback = () => {
      getSceneListFn();
    };
    const beforeTriggering = () => {
        ruleForm.collectTimeBefore = collectTimeBefore.value
    };
    const afterTriggering = () => {
        ruleForm.collectTimeAfter = collectTimeAfter.value
    };
    const countChange = () => {
        ruleForm.count = count.value
    };
    onMounted(() => {
      getSceneListFn();
      ruleForm.collectTimeBefore = collectTimeBefore.value
      ruleForm.collectTimeAfter = collectTimeAfter.value
      ruleForm.count = count.value
    });

    return {
      ruleForm,
      rules,
      ruleFormRef,
      statusOptions,
      newScene,
      submitForm,
      createScene,
      sceneOptions,
      feedback,
      returnBack,
      projectNameIsJ3,
      beforeTriggering,
      afterTriggering,
      collectTimeBefore,
      collectTimeAfter,
      countChange,
      count
    };
  },
};
</script>

<style lang="less">
.createPolicy {
  .crumbs {
    display: flex;
    align-items: center;
    padding: 10px;
    margin-top: 5px;
  }

  .content {
    padding: 20px;
    //background: #eeeeee;
    height: 100%;

    .main {
      padding: 20px;
      background: #ffffff;
      display: flex;
      justify-content: center;
    }
    .no-margin-left{
        margin-bottom: 20px;
        .el-form-item__content{
            margin-left: 0 !important;
        }
    }
  }
}
</style>
